#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <assert.h>

void read_cb(struct bufferevent *bev, void *arg) {
    char buf[1024] = {0};
    bufferevent_read(bev, buf, sizeof buf);
    printf("%s", buf);
}

void write_cb(struct bufferevent *bev, void *arg) {
    printf("[client]: write finished\n");
}

void event_cb(int fd, short what, void *arg) {
    char buf[1024] = {0};
    int len = read(fd, buf, sizeof buf);
    struct bufferevent* bev = (struct bufferevent *)arg;
    bufferevent_write(bev, buf, sizeof buf);
}

void ev_cb(struct bufferevent *bev, short what, void *arg) {
    if (what & BEV_EVENT_ERROR)  {
        printf("some other error\n");
    }
    if (what & BEV_EVENT_CONNECTED) {
        printf("[server]: connected success\n");
        return;
    }
    bufferevent_free(bev);    
    printf("buffevent 资源已经被释放...\n"); 
}


int main(int argc, char *argv[]) {
    if (argc < 3) {
        printf("usage %s: [ip] [port]\n", argv[0]);
        return 0;
    }
    int fd = socket(PF_INET, SOCK_STREAM, 0);
    struct event_base *evbase = event_base_new();
    struct sockaddr_in addr;
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
     
    struct bufferevent* bev = bufferevent_socket_new(evbase, fd, BEV_OPT_CLOSE_ON_FREE);
    bufferevent_socket_connect(bev, (struct sockaddr *)&addr, sizeof addr);
    
    bufferevent_setcb(bev, read_cb, write_cb, ev_cb, NULL);
    
    bufferevent_enable(bev, EV_READ);

    struct event *ev = event_new(evbase, STDIN_FILENO, EV_READ|EV_PERSIST, event_cb, (void *)bev);

    event_add(ev, NULL);
    event_base_dispatch(evbase);

    event_free(ev);
    event_base_free(evbase); 
    return 0;
}